package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.project.dao.SoilTemperatureDataDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.*;
import edu.ynu.se.xiecheng.achitectureclass.project.po.vo.EnvironmentVO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.vo.SoilTemperatureVO;
import edu.ynu.se.xiecheng.achitectureclass.project.utils.GreenhouseDeviceUtils;
import edu.ynu.se.xiecheng.achitectureclass.project.utils.SensorApiClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SoilTemperatureDataService extends LogicService<SoilTemperatureDataDAO, SoilTemperatureData, Long> {
    @Autowired
    private SensorApiClient sensorApiClient;

    @Autowired
    private GreenhouseDeviceUtils greenhouseDeviceUtils;

    private static final String[] DAYS_OF_WEEK = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

    public SoilTemperatureDataService(SoilTemperatureDataDAO lr) {
        super(lr);
    }


    /**
     * 获取最新的土壤温度数据，并以周为单位返回，用于前端展示
     * @return
     */
    public SoilTemperatureVO getLatestSoilTemperatureData() {
        // 获取最近7天的数据
        List<SoilTemperatureData> data = dao.findTop7ByOrderByTimestampDesc();

        // 创建一个Map来存储每天的温度数据
        Map<String, Double> temperatureMap = new HashMap<>();

        // 处理现有数据
        data.forEach(item -> {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(item.getTimestamp());
            // Calendar 中 1 是周日，2 是周一，需要转换
            int day = calendar.get(Calendar.DAY_OF_WEEK);
            // 转换为我们需要的格式（1 是周一，7 是周日）
            int adjustedDay = day == 1 ? 7 : day - 1;

            String dayOfWeek = getDayOfWeekInChinese(adjustedDay);
            temperatureMap.put(dayOfWeek, item.getValue());
        });

        // 准备返回数据
        List<Double> values = new ArrayList<>();
        List<String> dayOfWeeks = new ArrayList<>();

        // 确保所有天都有数据，没有的补0
        for (String day : DAYS_OF_WEEK) {
            dayOfWeeks.add(day);
            values.add(temperatureMap.getOrDefault(day, 0.0));
        }

        return new SoilTemperatureVO(values, dayOfWeeks);
    }

    /**
     * 获取星期几的中文表示
     * @param dayOfWeek
     * @return
     */
    private String getDayOfWeekInChinese(int dayOfWeek) {
        switch (dayOfWeek) {
            case 1: return "周一";
            case 2: return "周二";
            case 3: return "周三";
            case 4: return "周四";
            case 5: return "周五";
            case 6: return "周六";
            case 7: return "周日";
            default: return "";
        }
    }

    /**
     * 获取当前土壤温度
     * @return
     */
    public SoilTemperatureData getCurrentSoilTemperature() {
        SoilTemperatureData soilTemperatureData = dao.findFirstByOrderByTimestampDesc();

        if (soilTemperatureData != null){
            return soilTemperatureData;
        }else
            return new SoilTemperatureData();
    }

    public void fetchAndSaveSoilTemperatureData() {
        // 示例 Box 编号和传感器 ID 列表
        String boxNo = "300822040454";
        List<String> sensorIds = List.of("327061586065758015");

        // 调用外部接口获取传感器数据
        List<Map<String, Object>> sensorData = sensorApiClient.fetchSensorData(sensorIds, boxNo);

        for (Map<String, Object> data : sensorData) {
            System.out.println("Sensor data: " + data);

            // 创建或更新大棚信息
            String boxId = data.get("boxId").toString(); // 大棚 ID
            Greenhouse greenhouse = greenhouseDeviceUtils.getOrCreateGreenhouse(boxId);

            // 创建或更新设备信息
            String sensorId = data.get("id").toString(); // 传感器设备 ID
            String name = data.get("name").toString();
            Device device = greenhouseDeviceUtils.getOrCreateDevice(sensorId, name, greenhouse);

            //创建土壤温度数据实例并设置属性
            SoilTemperatureData soilTemperatureData = new SoilTemperatureData();
            soilTemperatureData.setName(name);
            soilTemperatureData.setValue(Double.parseDouble(data.get("value").toString()));
            soilTemperatureData.setUnit("℃");
            soilTemperatureData.setTimestamp(new Date());
            soilTemperatureData.setDevice(device);

            dao.save(soilTemperatureData);
        }
    }
}
